package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class AccessFilter extends ZuulFilter {
    // 过滤器的类型： pre, routing ,post ,error
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    // 顺序号，自己写的过滤器加在什么位置
    @Override
    public int filterOrder() {
        return 6;//加到前置过滤器的第六个
    }
    //针对当前请求，是否要执行过滤代码
    //请求商品检查权限，请求用户订单不检查权限
    @Override
    public boolean shouldFilter() {
        //判断当前调用扽后台服务，是不是  item-service

        //获得调用的id
        RequestContext context = RequestContext.getCurrentContext();
        String serviceId = (String) context.get(FilterConstants.SERVICE_ID_KEY);

        //如果id是item-service，返回true
        return "item-service".equals(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //RequestContext请求上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isAllBlank(token)){
            //阻止继续调用
            context.setSendZuulResponse(false);
            //直接返回响应
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("未登录").toString();
            context.addZuulResponseHeader("Content-Type","application/json;charset=utf-8");
            context.setResponseBody(json);

        }
        //zuul当前版本没有使用这个返回值，它不器任何作用。
        return null;
    }
}
